package com.doudou.dubbo.demo;

import com.doudou.dubbo.demo.api.GreetingService;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.remoting.exchange.ResponseCallback;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.protocol.dubbo.FutureAdapter;

/**
 * @author zhaozw
 * @version 1.0
 * @date 2025-07-22 16:23
 **/
public class APiAsyncConsumerForCallBack {

    public static void main(String[] args) throws InterruptedException {
        // 创建引用实例，并设置属性
        ReferenceConfig<GreetingService> referenceConfig = new ReferenceConfig<>();
        referenceConfig.setApplication(new ApplicationConfig("first-dubbo-consumer"));
        referenceConfig.setRegistry(new RegistryConfig("zookeeper://127.0.0.1:2181"));
        referenceConfig.setInterface(GreetingService.class);
        referenceConfig.setTimeout(5000);
        referenceConfig.setVersion("1.0.0");
        referenceConfig.setGroup("dubbo");

        // 设置为异步
        referenceConfig.setAsync(true);

        // 调用时结果会返回null
        GreetingService greetingService = referenceConfig.get();
        RpcContext.getContext().setAttachment("company", "juzi");
        String result = greetingService.sayHello("world");
        System.out.println("result: " + result);

        // 异步执行回调
        ((FutureAdapter) RpcContext.getContext().getFuture()).getFuture().setCallback(new ResponseCallback() {
            @Override
            public void done(Object o) {
                System.out.println("callback result: " + o);
            }

            @Override
            public void caught(Throwable throwable) {
                System.out.println("callback error: " + throwable.getLocalizedMessage());
            }
        });
        Thread.currentThread().join();
    }
}
